﻿using Cyss.Core;
using Cyss.Core.Api.Client;
using CyssBlazor.Shared.Infrastructure;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;

namespace CyssBlazor.WebAssembly.ServerHost.Controllers
{
    [ApiController]
    public class ConfigController : Controller
    {

        [HttpPost]
        [Route("Config/GetAssemblies")]
        public string GetAssemblies()
        {
            OperateResult<IEnumerable<string>> apiResponse = new OperateResult<IEnumerable<string>>();
            try
            {
                apiResponse.Data=AssembliesExtensions.UserAssemblies
                .Where(x => x.GetTypes().Any(t => t.IsInterface == false && t.GetInterfaces().Contains(typeof(BaseConfig))))
                .Select(x => x.ManifestModule.Name.Replace(".dll", ""));
                apiResponse.IsEncryption = true;
                apiResponse.IsSuccess = true;
                return JsonHelper.SerializeObject(apiResponse);

            }
            catch (Exception ex)
            {
                apiResponse.IsSuccess = false;
                return JsonHelper.SerializeObject(apiResponse);
            }

        }


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("Config/GetConfig")]
        public OperateResult<Dictionary<string, object>> GetConfig()
        {
            OperateResult<Dictionary<string, object>> apiResponse = new OperateResult<Dictionary<string, object>>();
            try
            {
                Dictionary<string, object> list = new Dictionary<string, object>();
                var types = AssembliesExtensions.UserAssemblies.SelectMany(a => a.GetTypes().Where(t => t.IsInterface == false && t.GetInterfaces().Contains(typeof(BaseConfig)))).ToArray();
                foreach (var type in types)
                {
                    var config = IOCEngine.Resolve(type);
                    list.Add(type.Name, config);
                }
                apiResponse.IsEncryption = true;
                apiResponse.Data = list;
                apiResponse.IsSuccess = true;
                return apiResponse;

            }
            catch (Exception ex)
            {
                apiResponse.IsSuccess = false;
                return apiResponse;
            }
        }
    }
}

